package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.pojo.Member;
import com.itheima.dao.MemberDao;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;

    @Override
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    @Override
    public void add(Member member) {
        if (member.getPassword() != null) {
            member.setPassword(MD5Utils.md5(member.getPassword()));
        }
        memberDao.add(member);
    }

    @Override
    public Map<String, Object> getMemberReport(Integer numTime) {
        //设置月份范围
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -numTime);

        ArrayList<String> listDate = new ArrayList<>();
        ArrayList<Integer> listNum = new ArrayList<>();

        for (int i = 0; i < numTime; i++) {
            calendar.add(Calendar.MONTH, 1);
            String date = new SimpleDateFormat("yyyy.MM").format(calendar.getTime());
            //添加日期
            listDate.add(date);
            //添加会员数
            Integer num = memberDao.findMemberCountBeforeDate(date);
            listNum.add(num);
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("months", listDate);
        map.put("memberCount", listNum);

        return map;
    }
}
